/**
 * 
 */
package bplustree;

import register.Register;
import register.RegisterID;

/**
 * @author ernesto
 *
 */
public class Leaf extends Node {

	private int nextLeaf;
	private int previousLeaf;
	
	/**
	 * 
	 */
	public Leaf(BPlusTree tree) {
		super(0,tree);
		nextLeaf=previousLeaf=this.getPosition();
	}
	
	
	
	/**
	 * @return the nextLeaf
	 */
	public int getNextLeaf() {
		return nextLeaf;
	}



	/**
	 * @param nextLeaf the nextLeaf to set
	 */
	public void setNextLeaf(int nextLeaf) {
		this.nextLeaf = nextLeaf;
	}



	/**
	 * @return the previousLeaf
	 */
	public int getPreviousLeaf() {
		return previousLeaf;
	}



	/**
	 * @param previousLeaf the previousLeaf to set
	 */
	public void setPreviousLeaf(int previousLeaf) {
		this.previousLeaf = previousLeaf;
	}



	protected void insert(Register reg) throws NodeOverflowException, DuplicateRegisterException{
		
		int tempPosition=getImmediateLess(reg.getID())+1; //posicion probable de insercion
		//System.out.println("Posicion de insercion tempPosition = " + tempPosition);
		// Verificacion de unicidad
		if(!registerList.isEmpty() && tempPosition>0){ //cubre el caso de lista vacia y de que el menor sea el ultimo
			//tempPosition<registerList.size()-1
			//System.out.println("Llega a comparar por colision");
			if(registerList.get(tempPosition-1).getID().compareTo(reg.getID())==0){
				//System.out.println("Registro Duplicado");
				throw new DuplicateRegisterException();
			}
		}
		
		registerList.add(tempPosition, reg);
		setFree_space(getFree_space()-reg.getSize());
		setRegister_count(getRegister_count()+1);
//		 Verificacion de tamaño
		//insercion directa??
		if(getFree_space()<0){
		//INSERCION CON OVERFLOWWW
			throw new NodeOverflowException();
		}
		
	}
	
	public Register search(RegisterID ID,RegisterIterator iterator) {
		iterator=new RegisterIterator(this,registerList.listIterator(getImmediateLess(ID)));
		return registerList.get(getImmediateLess(ID));
	}
	
	public RegisterIterator firstRegIterator() {
		return new RegisterIterator(this,registerList.listIterator());
	}
	
	public void modify(Register reg) throws NodeOverflowException {
		int tempPosition = getImmediateLess(reg.getID());
		registerList.get(tempPosition).merge(reg);
		if(getFree_space()<0){
			//MODIFICACION CON OVERFLOWWW
				throw new NodeOverflowException();
		}
		
	}

}
